<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者: 奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\controller;
use think\DB;
use think\facade\Request;
class User extends Base
{
	//用户信息列表
   public function index(){
     
      $alias = 'a';        //需要别名时写别名，不需要的时候留空 
      $defaultWhere = '';
      $defaultOrder = 'a.reg_time desc';
    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where = $SearchFormData['where'];
      $order = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];

//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'uid', //字段名
                  'name'    =>'用户UID', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'username',
                  'name'    =>'用户名',
                  'alias'   => $alias,
                  ]
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'登陆时间',  //标签显示名称
                  'field'        =>'login_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],
                  [
                  'title'        =>'注册时间',
                  'field'        =>'reg_time', 
                  'start_name'   =>'开始时间',
                  'end_name'     =>'结束时间',
                  'alias'        => $alias  //字段别名
                  ]
              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'=>'审核状态',
                             'field' => 'status', 
                             'data'  => [ 0 =>'等待审核',1=>'正常',-1=>'禁止访问'],
                             'alias'=>$alias,
                            ]
                       ]; 
// 组件字段组筛选
    $groupData = [
                    [
                     'name'      =>'用户组',     //用户组
                     'table'     =>'user_level', //表名
                     'field_id'  =>'level_id',   //字段ID
                     'field_name'=>'level_name',  //字段名
                     'alias'     => $alias,
                    ],
        
              ];
     $orderData   = [
                 [
                 'name'     =>'余额多到少',
                 'field'    =>'money',  //字段名
                 'orderby'  =>'desc',     //注册排序
                 'alias'    => $alias,         //数据表别名
                 ],
                 [
                 'name'     =>'余额少到多',
                 'field'    =>'money',
                 'orderby'  =>'asc',
                 'alias'    => $alias,
                 ],
                [
                 'name'     =>'保证金多到少',
                 'field'    =>'deposit',  //字段名
                 'orderby'  =>'desc',     //注册排序
                 'alias'    => $alias,    //数据表别名
                 ],
                 [
                 'name'     =>'保证金少到多',
                 'field'    =>'deposit',
                 'orderby'  =>'asc',
                 'alias'    => $alias,
                 ],
               ];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $list = DB::name('user')->alias('a')->join('user_level b','a.level_id = b.level_id',"LEFT")->where($where)->order($order)->paginate($pageNum);
     $page = $list->render();
     $count = $list->total();
     $this->assign('count', $count);
     $this->assign('page', $page);
     $this->assign('list', $list->toArray()['data']);
	  return $this->fetch();
	} 

//增加
  public function add(){
    $param = $this->request->param(); 
    if($this->request->isAjax()){   
   
        //验证
        $rule =[
          'username'=>'require|alphaDash',
          'password'=>'require|min:6',
          'repassword'=>'require|min:6',
        ];
        $msg= [
         'username.require' =>'用户名不能为空',
         'username.alphaDash' =>'用户名只能是字母和数字，下划线_及破折号-',
         'password.require' =>'登陆密码不能为空', 
         'password.min' =>'登陆密码至少6位',   
         'repassword.require' =>'重复密码不能为空', 
         'repassword.min' =>'重复密码至少6位',        
        ];

         if($error = $this->checkSubmit($param,$rule,$msg)){

              return error_json($error);
         }
         //表单数据
          $data['username'] = $param['username'];
          $data['nickname'] = !empty($param['nickname'])?$param['nickname']:$param['username'];
        

          if($param['password'] != $param['repassword']){
             return error_json('重复登陆密码不一致');  
          }
          // 登陆加密码
          $passsalt = random_text(8);
          $data['password'] = password_key($data['username'],$param['password'],$passsalt);
          $data['passsalt']  = $passsalt; 
           
          if($param['payword'] != $param['repayword']){
             return error_json('重复支付密码不一致');  
          }

           $paysalt = random_text(8); //支付密钥
          if($param['payword']){
            //支付密码存在
            $data['payword']  = payword_key($data['username'],$param['payword'],$paysalt);
            $data['paysalt']  = $paysalt;  

          }else{
            // 支付密码不存在，初始化密码为登陆密码
            $data['payword']  = payword_key($data['username'],$param['password'],$passsalt);
            $data['paysalt']  = $passsalt;  
          }


          $data['gender'] = !empty($param['gender'])?1:0; //0 男  1女  2保密
          $data['avatar'] = $param['avatar'];
          $data['level_id'] = $param['level_id'];
         //省份
          if($param['prov']){
              $data['provid'] = $param['prov'];     
          }
          //城市
          if($param['city']){
              $data['cityid'] = $param['city'];
          }
          // 地区
          if($param['dist']){
             $data['distid'] = $param['dist'];  
          }

           //是否实名认证
           if(!empty($param['is_realname'])){
                if($param['realname'] ==''){
                   return error_json('已实名认证，真实姓名必须存在');
                } 
           } 
           $data['is_realname'] = !empty($param['is_realname'])?$param['is_realname']:0;     
          //是否银行卡认证
           $data['is_bank']     = !empty($param['is_bank'])?$param['is_bank']:0; 
         //是否邮件认证
           $data['is_email']    = !empty($param['is_email'])?$param['is_email']:0; 
         //是否手机认证
           $data['is_mobile']   = !empty($param['is_mobile'])?$param['is_mobile']:0; 

          //银行卡信息
          
          $data['bank']      = $param['bank'];   //银行卡
          $data['bank_type'] = $param['bank_type']; //银行卡类型
          $data['branch']    = $param['branch']; //支行
          $data['account']   = $param['account']; //卡号或者支付平台账号
          
          $data['realname'] = $param['realname'];
          $data['mobile'] = $param['mobile'];
          $data['qq']     = $param['qq'];
          $data['email']  = $param['email'];
          $data['login_count'] = 0;
          $data['reg_time']    = time();
          $data['reg_ip'] = get_client_ip();
          $data['status'] = 1;
        //如果用户不存在则添加
        $where['username'] = $data['username'];
        $user = model('user')->infoData($where);
        if(!empty($user)){
         return error_json('该用户名已经存在，请勿重复添加');
        }

       if(model('user')->addData($data)){
         return success_json('添加成功'); 
       }
   }else{
        //获得用户组信息
        $list = model('UserLevel')->getUserLevelList();
        $this->assign('list',$list);
        return $this->fetch();
   }      
  }
  public function edit(){
    $param = $this->request->param();
    if($this->request->isAjax()){

           //验证
        $rule =[
           'id'=>'require',
          'username'=>'require|alphaDash',
        ];
        $msg= [
         'id.require' =>'请求参数错误',
         'username.require' =>'用户名不能为空',
         'username.alphaDash' =>'用户名只能是只能是字母和数字，下划线_及破折号-',
       
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
         if($error){
              return error_json($error);
         }
         //表单数据
     
          $data['nickname'] = !empty($param['nickname'])?$param['nickname']:$param['username'];
        
         
          if(!empty($param['password'])){
            if($param['password'] != $param['repassword']){
               return error_json('重复登陆密码不一致');  
            }
            $where['uid'] = $param['id'];
            $user = model('user')->infoData($where);
            $passsalt = random_text(8); //登陆加密码
            $data['password'] = password_key($user['username'],$param['password'],$user['passsalt']);
            
          }
          
          if(!empty($param['payword'])){
                if($param['payword'] != $param['repayword']){
                  return success_json('重复支付密码不一致');  
                }
                
           $data['payword'] = payword_key($user['username'],$param['payword'],$user['paysalt']);
               
          }

        

          $data['gender']   = !empty($param['gender'])?1:0; //0 男  1女  2保密
          $data['avatar']   = $param['avatar'];
          $data['level_id'] = $param['level_id'];
         //省份
          if($param['prov']){
              $data['provid'] = $param['prov'];     
          }
          //城市
          if($param['city']){
              $data['cityid'] = $param['city'];
          }
          // 地区
          if($param['dist']){
             $data['distid'] = $param['dist'];  
          }


           //是否实名认证
           if(!empty($param['is_realname'])){
                if($param['realname'] ==''){
                   return error_json('已实名认证，真实姓名必须存在');
                } 
           } 
           $data['is_realname'] = !empty($param['is_realname'])?$param['is_realname']:0;     
          //是否银行卡认证
           $data['is_bank']     = !empty($param['is_bank'])?$param['is_bank']:0; 
         //是否邮件认证
           $data['is_email']    = !empty($param['is_email'])?$param['is_email']:0; 
         //是否手机认证
           $data['is_mobile']   = !empty($param['is_mobile'])?$param['is_mobile']:0; 

          $data['bank']      = $param['bank'];   //银行卡
          $data['bank_type'] = $param['bank_type']; //银行卡类型
          $data['branch']    = $param['branch']; //支行
          $data['account']   = $param['account']; //卡号或者支付平台账号
          
          $data['realname'] = $param['realname']; //实名
          $data['mobile'] = $param['mobile'];
          $data['qq']     = $param['qq'];
          $data['email']  = $param['email'];
          $data['status'] = $param['status'];         
          $where['uid']   = $param['id'];
          $res = model('user')->editData($data,$where);
        
          return success_json('编辑成功'); 
    }else{
         $user = model('user')->getUserByUid($param['id']);
         $this->assign('user',$user);

         //显示会员组
         $UserLevel = model('UserLevel')->getUserLevelList();
         $this->assign('UserLevel',$UserLevel);       
         return $this->fetch();


    }  
  }
  public function del(){
      $param = input();
     if(!$param['id']){  return error_json('请求参数错误');    }
       $res= $this->delData('user','uid',$param['id']);
       if($res){
        return success_json('删除成功');
       }else{
        return error_json($res);
       }
  }


   public function show(){
      $username = input("get.username");
      $user =  model('user')->getUserByUsername($username);
      $this->assign('user', $user);
      return $this->fetch();
   }

//增减资金
  public function money(){
    $param = $this->request->param(); 
    if($this->request->isPost()){   
        //验证
        $rule =[
          'username'=>'require',
          'type'=>'require',
          'amount'=>'require',
          'bankname'=>'require',
          'remark'=>'require',
        ];
        $msg= [
         'username.require' =>'用户名不能为空',
         'type.require' =>'类型不能为空', 
         'amount.require' =>'金额不能为空',
         'bankname.require' =>'支付方式不能为空',
         'remark.require' =>'备注不能为空',    
        ];
         $error = $this->checkSubmit($param,$rule,$msg);  
       if($error){
              return error_json($error);
         }

         //表单数据
          $data['username'] = $param['username'];
          $data['type'] = $param['type'];
          $data['bankname'] = $param['bankname'];
          $data['remark'] = $param['remark'];
          $data['editor'] = session('admin_username'); //操作的管理员
          $data['create_time'] =time();  

          $user = model('user')->getUserByUsername($param['username']);   
          if($param['type'] ==1){
            $data['amount'] = -$param['amount'];
            //查询用户余额是否充足
             $user = model('user')->getUserByUsername($param['username']);  
             if($user['money'] < abs($data['amount'])){
                 return error_json('余额不足');
              }
         
            //扣除用户余额，并且自动增加一条记录
             model('user')->payout($user['uid'],$param['amount'],$param['remark'],$param['bankname']);

            //发送站内消息
             model('message')->send($user['uid'],'余额扣除提醒','系统从您的余额中扣除了'.$param['amount'].'元');

             return success_json('资金扣除成功');
          }else{
            $data['amount'] = $param['amount'];

          //用户余额充值，并且自动增加一条记录
            model('user')->payin($user['uid'],$param['amount'],$param['remark'],$param['bankname']);

           //发送站内消息
            model('message')->send($user['uid'],'余额充值提醒','系统给您的余额充值了'.$param['amount'].'元');

            return success_json('资金增加成功');
  
          }

   }else{
        return $this->fetch();
   }      
  }

//积分奖惩
   public function credit(){
      $param = $this->request->param(); 
      if($this->request->isPost()){   

          //验证
          $rule =[
            'username'=>'require',
            'type'=>'require',
            'amount_credit'=>'require',
            'note'=>'require',
          ];
          $msg= [
           'username.require' =>'用户名不能为空',
           'type.require' =>'类型不能为空', 
           'amount_credit.require' =>'积分数量不能为空',
           'note.require' =>'备注不能为空',    
          ];
           $error = $this->checkSubmit($param,$rule,$msg);  
         if($error){
                return error_json($error);
           }

           //表单数据
            $data['username'] = $param['username'];
            $data['type'] = $param['type'];
            $data['note'] = $param['note'];
            $data['editor'] = session('admin_username'); //操作的管理员
            $data['create_time'] =time();  


            if($param['type'] ==1){
              $data['amount_credit'] = -$param['amount_credit'];
              //查询用户积分是否充足
               $user = model('user')->getUserByUsername($param['username']);  
               if($user['credit'] < abs($data['amount_credit'])){
                   return error_json('积分不足');
                }
              //减少积分
              model('user')->where("username = '".$param['username']."'")->setDec('credit',$param['amount_credit']);

              // 增加积分支出记录
               $user = model('user')->getUserByUsername($param['username']);        
               $data['balance_credit'] = $user['credit'];
               model('finance_credit')->addData($data);
               return success_json('积分扣除成功');
            }else{
              $data['amount_credit'] = $param['amount_credit'];
              //增加积分
              model('user')->where("username = '".$param['username']."'")->setInc('credit',$param['amount_credit']);
              
           // 增加积分收入记录
               $user = model('user')->getUserByUsername($param['username']);        
               $data['balance_credit'] = $user['credit'];
               model('finance_credit')->addData($data);
               // echo  model('user')->getLastSql();
               return success_json('积分奖励成功');
    
            }

       
   


     }else{
          return $this->fetch();
      } 

   }

//禁止访问
	public function ban(){
     $param = $this->request->param(); 
     if($this->request->isAjax()){
       if($param['type'] != -1){  return error_json('参数错误');}
          $uid = $param['id'];
          $userinfo = model('user')->getUserByUid($param['type']);
          $data['status'] = -1;
           if(is_array($uid)){
             $idData = implode(',',$uid);
          }else{
             $idData = $uid;
          }
          
          $where ="uid IN ($idData)";
          model('user')->editData($data,$where);
          return success_json('更新成功');

     }

  }

   public function userSelect()
   {
        $alias = 'a';        //需要别名时写别名，不需要的时候留空 
        $defaultWhere = '';
        $defaultOrder = 'a.reg_time desc';
      //接收搜索表单数据
        $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
        $where = $SearchFormData['where'];
        $order = $SearchFormData['order'];
        $pageNum = $SearchFormData['pageNum'];

  //组建关键词数据
       $keywordsData  =[
                    [
                    'field'   =>'uid', //字段名
                    'name'    =>'用户UID', //文本显示名称
                    'alias'   => $alias,  //字段对应的别名
                    ],
                    [
                    'field'   =>'username',
                    'name'    =>'用户名',
                    'alias'   => $alias,
                    ]
       ];
  //组建日期筛选   
         $dateData = [

                ];
  //单个字段筛选
      $customSingleField =[
                         ]; 
  // 组件字段组筛选
      $groupData = [];
       $orderData   = [
            
                 ];  

       $this->assign('keywordsData',$keywordsData);
       $this->assign('customSingleField',$customSingleField);
       $this->assign('groupData',$groupData);
       $this->assign('dateData',$dateData);
       $this->assign('orderData',$orderData);


       $list = DB::name('user')->alias('a')->join('user_level b','a.level_id = b.level_id',"LEFT")->where($where)->order($order)->paginate($pageNum);
       $page = $list->render();
       $count = $list->total();
       $this->assign('count', $count);
       $this->assign('page', $page);
       $this->assign('list', $list->toArray()['data']);
      return $this->fetch();
   }
}